<template>
  <div class="bind-phone-container">
    <div class="box-card">
      <div class="title">换绑手机号</div>
      <div class="bind-wrap">
        <el-form :model="phoneOptions" ref="phoneForm" class="form" label-width="90px" :rules="rules">
          <el-form-item label="手机号：">
            <span class="content-info">{{phoneOptions.oldMobile | hidePhoneFourRank}}</span>
          </el-form-item>
           <el-form-item label="新手机号："  prop="newMobile">
            <el-input class="code" type="tel" maxlength="11" v-model="phoneOptions.newMobile"  autocomplete="off" placeholder="请输入新手机号"></el-input>
          </el-form-item>
          <el-form-item label="验证码："  prop="verificationCode">
            <el-input class="code" type="text" v-model="phoneOptions.verificationCode"  maxlength="4" autocomplete="off" placeholder="请输入验证码"></el-input>
            <el-button @click="toSendCode" :disabled="isSending" class="send-btn" :style="{padding: paddingType}" v-loading="sendLoading">
              <span style="font-size: 14px">{{codeText}}</span>
            </el-button>
          </el-form-item>
          <div class="btn-wrap">
            <el-button type="primary" class="primary" :loading="bindLoading" @click="handleBind">绑定</el-button>
          </div>
      </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { validPhone } from '@/utils/utils'
import { rebindSendCode, changeBindPhone } from '@/api/account'
import store from '@/store'
export default {
  data () {
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入手机号码'))
      } else if (!validPhone(value)) {
        return callback(new Error('手机号码格式不正确'))
      } else {
        callback()
      }
    }
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入验证码'))
      } else {
        callback()
      }
    }
    return {
      sendLoading: false,
      bindLoading: false,
      phoneOptions: {
        oldMobile: '',
        newMobile: '',
        verificationCode: ''
      },
      codeText: '发送验证码',
      isSending: false,
      rules: {
        newMobile: [
          { validator: checkPhone, trigger: 'blur' }
        ],
        verificationCode: [
          { validator: checkCode, trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.phoneOptions.oldMobile = this.userInfo.mobile
  },
  computed: {
    ...mapState('user', {
      userInfo: state => state.userInfo
    }),
    paddingType () {
      let {isSending} = this
      if (isSending) {
        return '0'
      } else {
        return '0 10px 0 10px'
      }
    }
  },
  methods: {
    toSendCode () {
      this.$refs.phoneForm.validateField('newMobile', errMsg => {
        if (errMsg) {
          return false
        } else {
          this.sendCode()
        }
      })
    },
    setCountText () {
      this.codeText = '60s后重新发送'
      let count = 60
      let timer = setInterval(() => {
        this.codeText = `${count}s后重新发送`
        if (count === 0) {
          clearInterval(timer)
          this.isSending = false
          this.codeText = '发送验证码'
        } else {
          count--
          this.codeText = `${count}s后重新发送`
        }
      }, 1000)
    },
    async sendCode () {
      this.sendLoading = true
      let { phoneOptions: { newMobile } } = this
      try {
        const { code } = await rebindSendCode({ mobile: newMobile })
        if (code !== 200) return
        this.isSending = true
        this.setCountText()
      } catch (error) {
        console.log(error.message)
      } finally {
        this.sendLoading = false
      }
    },
    handleBind () {
      const { oldMobile } = this.phoneOptions
      if (!oldMobile) return
      this.$refs.phoneForm.validate((valid) => {
        if (valid) {
          this.$confirm('是否确认换绑此手机号', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            center: true
          }).then(() => {
            this.changeBindPhone()  
          }).catch(() => {
            this.$message('已取消')
          })
        } else {
          return false
        }
      })
    },
    async changeBindPhone () {
      this.bindLoading = true
      const params = {
        newMobile: this.phoneOptions.newMobile,
        oldMobile: this.phoneOptions.oldMobile,
        verityCode: this.phoneOptions.verificationCode
      }
      try {
        const { code, result } = await changeBindPhone(params)
        if (code !== 200) return
        let userInfo = { ...this.userInfo, mobile: params.newMobile, multipleAccounts: result.multipleAccounts }
        await this.$store.dispatch('user/setUserInfo', JSON.parse(JSON.stringify(userInfo)))
        this.$message.success('换绑成功')
        setTimeout(() => {
          this.$router.replace({ name: 'myAccount' })
        }, 1000);
      } catch (error) {
        console.log(error.message)
      } finally {
        this.bindLoading = false
      }
    },
    // 退出登录
    logout () {
      store.dispatch('permission/resetPermission')
      store.dispatch('user/clearInfo')
    }
  }
}
</script>

<style lang="less" scoped>
.bind-phone-container{
  width: 100%;
  height: 100%;
  background: rgba(248,249,253,1);
  padding: 30px 20px 0 20px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-size: 14px;
  .box-card{
    width: 100%;
    padding: 20px 20px 63px 20px;
    background-color: #fff;
    .title{
      font-size: 18px;
      font-weight: 500;
      color: #333333;
    }
    .bind-wrap{
      margin: 20px 0;
      .content-info{
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #666666;
        margin-right: 15px;
      }
      .code{
        width: 163px;
        height: 40px;
        margin-right: 8px;
      }
      .send-btn{
        width: 102px;
        height: 40px;
        border-radius: 4px;
        border: 1px solid #4765F9;
        background-color: rgba(71, 101, 249, 0.09);
        color: #4765F9;
      }
    }
  }
}
/deep/.el-form-item__label{
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #222222;
}
.btn-wrap{
  margin-top: 50px;
  padding-left: 70px;
  box-sizing: border-box;
  font-size: 14px;
  font-family: PingFangSC-Medium, PingFang SC;
  /deep/.el-button.primary {
    width: 120px;
    height: 40px;
    padding: 0px 10px 0 10px;
    background-color: #4B7EFE;
    border-radius: 2px;
    border:none;
    margin-right: 20px;
    font-weight: 500;
  }
  /deep/.el-button.none {
    width: 120px;
    height: 40px;
    padding: 0px 10px 0 10px;
    border-radius: 2px;
    color: #666;
  }
}
</style>